package com.teachlearnweb.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.stereotype.Service;

import com.teachlearnweb.service.BookService;
import com.teachlearnweb.service.vo.BookVO;

@Service(value="bookService")
public class BookServiceImpl implements BookService {
	private List<BookVO> books = Collections.synchronizedList(new ArrayList<BookVO>());

	public BookServiceImpl() {
		books.add(new BookVO("AspectJ in Action, Second Edition", "Ramnivas Laddad", Long.valueOf("1933988053")));
		books.add(new BookVO("ActiveMQ in Action", "Bruce Snyder, Dejan Bosanac, and Rob Davies", Long.valueOf("1933988940")));
		books.add(new BookVO("Hadoop in Action", "Chuck Lam", Long.valueOf("9781935182191")));
		books.add(new BookVO("JUnit in Action, Second Edition", "Petar Tahchiev, Felipe Leme, Vincent Massol, and Gary Gregory", Long.valueOf("9781935182023")));
	}

	public List<BookVO> getBooks() {
		return books;
	}

	public void addBook(BookVO book) {
		System.out.println("In Service............");
		books.add(book);
	}

	public void removeBook(Long isbnNumber) {
		synchronized(books) {
			books.remove(getBook(isbnNumber));
		}
	}
	
	public boolean isUniqueISBN(Long isbnNumber) {
		boolean isUnique = true;
		for(BookVO book : books) {
			if(book.getIsbnNumber().equals(isbnNumber)) {
				isUnique = false;
				break;
			}
		}
		return isUnique;
	}

	public BookVO getBook(Long isbnNumber) {
		BookVO matchingBook = null;
		BookVO returnBook = null;

		synchronized (books) {
			for (BookVO book : books) {
				if (book.getIsbnNumber().equals(isbnNumber)) {
					matchingBook = book;
					break;
				}
			}
			// --create shallow copy of the Book object
			if (matchingBook != null) {
				returnBook = new BookVO();
				returnBook.setAuthor(matchingBook.getAuthor());
				returnBook.setIsbnNumber(matchingBook.getIsbnNumber());
				returnBook.setName(matchingBook.getName());
			}
		}
		return returnBook;
	}
	
	public void editBook(BookVO book) {
		Long isbnNumber = book.getIsbnNumber();
		BookVO matchingBook = null;
		
		synchronized (books) {
			for (BookVO book_ : books) {
				if (book_.getIsbnNumber().equals(isbnNumber)) {
					matchingBook = book_;
					break;
				}
			}
			books.remove(matchingBook);
			books.add(book);
		}
	}
}
